package org.jinxing.utils;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailSendUtil {
	private JavaMailSender mailSender;
	private SimpleMailMessage mailMessage;
	public JavaMailSender getMailSender() {
		return mailSender;
	}

	public void setMailSender(JavaMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public SimpleMailMessage getMailMessage() {
		return mailMessage;
	}

	public void setMailMessage(SimpleMailMessage mailMessage) {
		this.mailMessage = mailMessage;
	}
	/**
	 * 发送邮件
	 * @param subject  邮件主题
	 * @param body     邮件内容
	 * @param to   邮件接收者
	 * @return true 发送成功 false 发送失败
	 */
	public boolean send(String subject, String body, String[] to) {
		SimpleMailMessage msg = new SimpleMailMessage(this.mailMessage);
		msg.setSubject(subject);
		msg.setText(body);
		msg.setTo(to);
		try {
			mailSender.send(msg);
			return true;
		} catch (MailException ex) {
			ex.printStackTrace();
			return false;
		}
	}
	/**
	 * 发送邮件
	 * @param subject  邮件主题
	 * @param body     邮件内容
	 * @param to   邮件接收者
	 * @return true 发送成功 false 发送失败
	 */
	public boolean sendHTML(String subject, String body, String to,String from) {
		try{
			 // 建立邮件讯息
	        MimeMessage mailMessage = mailSender.createMimeMessage();
	        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);
	        // 设定收件人、寄件人、主题与内文
	        messageHelper.setTo(to);
	        messageHelper.setFrom(from);
	        messageHelper.setSubject(subject);
	        messageHelper.setText(body, true);
	        // 传送邮件
	        mailSender.send(mailMessage);
	        return true;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
    }
}
